package com.yzmoney.common.util;

import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.util.Assert;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

public final class JsonUtils {
    private static final Log log = LogFactory.getLog(JsonUtils.class);

    /**
     * ObjectMapper
     */
    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * 不可实例化
     */
    private JsonUtils() {
    }

    public static String toJson(Object value) {
        try {
            return mapper.writeValueAsString(value);
        } catch (Exception e) {
            log.warn(JDKStackTrace.getJDKStrack(e));
        }
        return null;
    }

    public static <T> T toObject(String json, Class<T> valueType) {
        Assert.hasText(json);
        Assert.notNull(valueType);
        try {
            return mapper.readValue(json, valueType);
        } catch (Exception e) {
            log.warn(JDKStackTrace.getJDKStrack(e));
        }
        return null;
    }

    public static <T> T toObject(String json, TypeReference<?> typeReference) {
        Assert.hasText(json);
        Assert.notNull(typeReference);
        try {
            return mapper.readValue(json, typeReference);
        } catch (Exception e) {
            log.warn(JDKStackTrace.getJDKStrack(e));
        }
        return null;
    }

    public static <T> T toObject(String json, JavaType javaType) {
        Assert.hasText(json);
        Assert.notNull(javaType);
        try {
            return mapper.readValue(json, javaType);
        } catch (Exception e) {
            log.warn(JDKStackTrace.getJDKStrack(e));
        }
        return null;
    }

    public static void writeValue(Writer writer, Object value) {
        try {
            mapper.writeValue(writer, value);
        } catch (JsonGenerationException e) {
            log.warn(JDKStackTrace.getJDKStrack(e));
        } catch (JsonMappingException e) {
            log.warn(JDKStackTrace.getJDKStrack(e));
        } catch (IOException e) {
            log.warn(JDKStackTrace.getJDKStrack(e));
        }
    }

    /**json to map*/
    public static Map toMap(String jsonSrc) {
        try {
            JSONObject obj = JSONObject.fromObject(jsonSrc);
            Map map = (Map) JSONObject.toBean(obj, Map.class);

            return map;
        } catch (Exception e) {
            log.warn(JDKStackTrace.getJDKStrack(e));
        }
        return null;
    }
    public static boolean jsonValidate(String jsonStr) {
        if (jsonStr == null || "".equals(jsonStr) || JsonUtils.toJson(jsonStr) == null) {
            return false;
        }
        return true;
    }

}